<template>
  <div class="flex-c flex-wrap">
    <div v-for="(item, index) in selectFileList" :key="index"  class="customHover w-100px h-100px relative overflow-hidden border-rd-4px mr-10px">
      <!-- 遮罩 -->
      <div class="customShadow absolute z-100 left-0px right-0px top-0px bottom-0px flex-cc hidden" style="background-color: rgba(0, 0, 0, 0.3);">
        <img @click="deleteImg(index)" class="w-20px h-20px cursor-pointer" src="@/assets/imgs/home/deleteImg.png" />
        <img @click="previewImg(item.src)" class="w-20px h-20px ml-10px cursor-pointer" src="@/assets/imgs/home/expandImg.png" />
      </div>
      <img class="w-100px h-100px "  :src="item.src"   />
    </div>
    <!-- 新增图片 -->
    <div v-if="selectFileList.length < limit" @click="selectFile" class="cursor-pointer w-100px h-100px bg-#F0F2F5 box-border border-rd-4px border-(1px solid #C7C7C7) flex-cc">
      <img class="w-14px h-14px" src="@/assets/imgs/home/addImg.png" />
    </div>
  </div>
  <input class="w-0px h-0px" ref="file" type="file" @change="selectFileChange" :accept="accept" />
  <ElImageViewer v-if="showViewer" :url-list="imgList" :initial-index="0" @close="showViewer = false" ></ElImageViewer>
</template>
<script setup lang="ts">
  import { ref,watch } from 'vue'
  import { ElImageViewer } from "element-plus";
  const props = defineProps({
    //允许文件格式
    accept: {
      type: String,
      default: '.png,.jpg,.jpeg,.gif'
    },
    //限制数量
    limit: {
      type: Number,
      default: 1
    },
    //fileList已经上传的文件数组
    fileList: {
      type: Array,
      default: () => []
    }
  })
  const emit = defineEmits(['update:fileList'])
  const file = ref<any>()

  //已选择的文件列表
  const selectFileList = ref<any[]>([])
  //是否展示图片预览组件
  const showViewer = ref(false)
  //预览图片数组
  const imgList = ref<any>([])
  //预览图片方法
  const previewImg = (val) => {
    imgList.value = [val]
    showViewer.value = true
  }
  //选择文件
  const selectFile = () => {
    file.value.click()
  }
  //选择文件发生改变
  const selectFileChange = () => {
    
    if(file.value.files[0]){
      let reader =  new FileReader()
      reader.onload = function (e) {
        file.value.files[0].src = e.target.result
        selectFileList.value = [...selectFileList.value, file.value.files[0]]
      }
      reader.readAsDataURL(file.value.files[0])
    }
  }

  //删除图片方法
  const deleteImg = (index) => {
    let tempArr = selectFileList.value.filter((item,aindex) => index != aindex)
    selectFileList.value = tempArr
  }

  //监听选择的文件发生改变
  watch( () => selectFileList.value, (val) => {
    emit('update:fileList', val)
  })
</script>
<style lang="less" scoped>
.customHover:hover{
  .customShadow{
    display: flex !important;
  }
}
</style>